<?php

namespace App\Console\Commands;

use App\Enum\TravelEnum;
use App\Models\OrderExtendModel;
use App\Services\QrcodeService;
use Illuminate\Console\Command;

class OrderQrcodeGenerateCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'qrcode:order {num_per_each?}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '生成订单的qrcode';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        while(1) {
            $second = date('s');
            $sleepRatio = 1;
            $sleep = 1;

            if ($second >= 56) {
                $this->info("second = $second, wait for next time.");
                break;
            } else  $this->info("second = $second, keep going.");
            $num = $this->argument('num_per_each') ?? 1;


            $oes = OrderExtendModel::query()->whereNull('qrcode_url')->select('order_id')->orderBy('id')->limit($num)->get();
            if (!empty($oes)) {
                try {
                    $oes = $oes->toArray();
                    foreach ($oes as $oe) {
                        $orderId = $oe['order_id'];
                        $url = sprintf(TravelEnum::QRCODE_INFO_URL[TravelEnum::QRCODE_TYPE_ORDER], env('BASE_URL'), $orderId);
                        $codeUrl = QrcodeService::getQrcode($url, $orderId, 'qrcode/'.env('APP_ENV'));
                        OrderExtendModel::query()->where(['order_id' => $orderId])->update(['qrcode_url' => $codeUrl]);
                    }
                } catch (\Exception $e) {
                    $this->info($e->getMessage());
                }
            }else $sleepRatio = 5;

            sleep($sleep*$sleepRatio);
        }

        return 0;
    }
}
